<template>
  <view class="filter-tabs">
    <view
      class="tab"
      v-for="(tab, index) in tabs"
      :key="index"
      :class="{ active: activeTab === tab.value }"
      @click="handleTabClick(tab)"
    >
      <block v-if="tab.value === 'area'">
        <picker mode="selector" :range="areaOptions" range-key="name" :value="selectedAreaIndex" @change="onAreaDirectChange">
          <view class="tab-content">{{ getTabDisplayName(tab) }}</view>
        </picker>
      </block>
      <block v-else>
        {{ getTabDisplayName(tab) }}
      </block>
    </view>
    
    <!-- 日期选择弹出层 -->
    <uni-popup ref="datePopup" type="center">
      <view class="popup-content">
        <view class="popup-title">选择日期范围</view>
        <view class="date-picker-container">
          <view class="date-item">
            <text>开始日期：</text>
            <picker mode="date" :value="tempStartDate || startDate" @change="onStartDateChange">
              <view class="picker-value">{{tempStartDate || startDate || '请选择'}}</view>
            </picker>
          </view>
          <view class="date-item">
            <text>结束日期：</text>
            <picker mode="date" :value="tempEndDate || endDate" :start="tempStartDate || startDate" @change="onEndDateChange">
              <view class="picker-value">{{tempEndDate || endDate || '请选择'}}</view>
            </picker>
          </view>
        </view>
        <view class="popup-buttons">
          <button class="btn cancel" @click="cancelDatePicker">取消</button>
          <button class="btn confirm" @click="confirmDatePicker">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import * as land from '@/utils/api/land.js';

export default {
  name: 'FilterTabs',
  props: {
    activeTab: {
      type: String,
      default: 'all'
    }
  },
  data() {
    return {
      tabs: [
        { name: "全部记录", value: "all" },
        { name: "最近7天", value: "recent" },
        { name: "本月", value: "month" },
        { name: "按日期", value: "date" },
        { name: "按地块", value: "area" },
      ],
      // 日期筛选
      startDate: '',
      endDate: '',
      tempStartDate: '',
      tempEndDate: '',
      
      // 地块筛选
      areaOptions: [
        { id: 0, name: '选择地块' }
      ],
      selectedAreaIndex: 0,
      
      // 当前选中的地块名称（用于回显）
      selectedAreaName: '',
      
      // 是否已选择自定义日期
      hasCustomDateSelected: false
    };
  },
  created() {
    // 组件创建时获取地块数据
    this.fetchAreaOptions();
  },
  methods: {
    // 获取地块数据
    async fetchAreaOptions() {
      try {
        const res = await land.getAllParcelAndFields();
        
        if (res.code === 0 && res.data && res.data.length > 0) {
          // 保留"选择地块"选项
          this.areaOptions = [
            { id: 0, name: '选择地块' },
            ...res.data.map(parcel => ({
              id: parcel.id,
              name: parcel.parcelName
            }))
          ];
        } else {
          // 接口请求失败，使用默认数据
          this.initDefaultAreaOptions();
        }
      } catch (error) {
        console.error('获取地块数据失败:', error);
        // 发生错误时使用默认数据
        this.initDefaultAreaOptions();
      }
    },
    
    // 初始化默认地块数据
    initDefaultAreaOptions() {
      this.areaOptions = [
        { id: 0, name: '选择地块' },
        { id: 1, name: '1号地块' },
        { id: 2, name: '2号地块' },
        { id: 3, name: '3号地块' },
        { id: 4, name: '4号地块' },
        { id: 5, name: '5号地块' }
      ];
    },
    
    // 获取选项卡显示名称（带回显）
    getTabDisplayName(tab) {
      if (tab.value === 'date' && this.hasCustomDateSelected && this.startDate && this.endDate) {
        return `${this.formatDisplayDate(this.startDate)} 至 ${this.formatDisplayDate(this.endDate)}`;
      } else if (tab.value === 'area') {
        return this.selectedAreaName || tab.name;
      } else {
        return tab.name;
      }
    },
    
    // 格式化显示日期（MM-DD）
    formatDisplayDate(dateStr) {
      if (!dateStr) return '';
      const parts = dateStr.split('-');
      if (parts.length >= 3) {
        return `${parts[1]}-${parts[2]}`;
      }
      return dateStr;
    },
    
    // 选项卡点击
    handleTabClick(tab) {
      if (tab.value === 'date') {
        // 打开日期选择弹窗
        this.tempStartDate = this.startDate || '';
        this.tempEndDate = this.endDate || '';
        this.$refs.datePopup.open();
      } else if (tab.value === 'area') {
        // 地块选择现在直接在选项卡中通过picker实现
        // 不需要额外处理
      } else if (tab.value === 'recent') {
        // 直接计算最近7天的日期范围
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - 7);
        
        this.startDate = this.formatDate(startDate);
        this.endDate = this.formatDate(endDate);
        this.hasCustomDateSelected = false;
        
        this.emitFilterChange(tab.value);
      } else if (tab.value === 'month') {
        // 直接计算本月的日期范围
        const now = new Date();
        const startDate = new Date(now.getFullYear(), now.getMonth(), 1);
        const endDate = new Date();
        
        this.startDate = this.formatDate(startDate);
        this.endDate = this.formatDate(endDate);
        this.hasCustomDateSelected = false;
        
        this.emitFilterChange(tab.value);
      } else {
        // 普通选项卡点击
        // 重置日期和地块选择
        if (tab.value === 'all') {
          this.resetAllFilters();
        }
        this.emitFilterChange(tab.value);
      }
    },
    
    // 地块直接选择变化
    onAreaDirectChange(e) {
      const index = e.detail.value;
      if (index > 0) { // 跳过"选择地块"选项
        this.selectedAreaIndex = index;
        this.selectedAreaName = this.areaOptions[index].name;
        
        // 直接触发筛选
        this.emitFilterChange('area');
      } else {
        // 选择了"选择地块"选项，重置地块筛选
        this.selectedAreaIndex = 0;
        this.selectedAreaName = '';
        this.emitFilterChange('all');
      }
    },
    
    // 重置所有筛选条件
    resetAllFilters() {
      this.startDate = '';
      this.endDate = '';
      this.tempStartDate = '';
      this.tempEndDate = '';
      this.selectedAreaIndex = 0;
      this.selectedAreaName = '';
      this.hasCustomDateSelected = false;
    },
    
    // 格式化日期为 YYYY-MM-DD
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 开始日期变化
    onStartDateChange(e) {
      this.tempStartDate = e.detail.value;
      
      // 如果结束日期已选择且早于新的开始日期，则清空结束日期
      if (this.tempEndDate && this.tempEndDate < this.tempStartDate) {
        this.tempEndDate = '';
      }
    },
    
    // 结束日期变化
    onEndDateChange(e) {
      this.tempEndDate = e.detail.value;
      
      // 验证结束日期不早于开始日期
      if (this.tempStartDate && this.tempEndDate < this.tempStartDate) {
        uni.showToast({
          title: '结束日期不能早于开始日期',
          icon: 'none'
        });
        this.tempEndDate = this.tempStartDate;
      }
    },
    
    // 确认日期筛选
    confirmDatePicker() {
      if (this.tempStartDate && this.tempEndDate) {
        // 再次验证日期范围
        if (this.tempEndDate < this.tempStartDate) {
          uni.showToast({
            title: '结束日期不能早于开始日期',
            icon: 'none'
          });
          return;
        }
        
        this.startDate = this.tempStartDate;
        this.endDate = this.tempEndDate;
        this.hasCustomDateSelected = true;
        this.$refs.datePopup.close();
        this.emitFilterChange('date');
      } else {
        uni.showToast({
          title: '请选择开始和结束日期',
          icon: 'none'
        });
      }
    },
    
    // 取消日期筛选
    cancelDatePicker() {
      // 恢复为之前的选择
      this.tempStartDate = this.startDate;
      this.tempEndDate = this.endDate;
      this.$refs.datePopup.close();
    },
    
    // 向父组件发送筛选变化
    emitFilterChange(tabValue) {
      let filterData = { type: tabValue };
      
      if (tabValue === 'date' || tabValue === 'recent' || tabValue === 'month') {
        filterData.startDate = this.startDate;
        filterData.endDate = this.endDate;
      } else if (tabValue === 'area' && this.selectedAreaIndex > 0) {
        filterData.areaId = this.areaOptions[this.selectedAreaIndex].id;
        filterData.areaName = this.areaOptions[this.selectedAreaIndex].name;
      }
      
      this.$emit('tab-change', tabValue, filterData);
    }
  }
};
</script>

<style lang="scss">
.filter-tabs {
  background-color: #fff;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 20rpx 10rpx 30rpx;

  .tab {
    flex: 0 1 18%;
    padding: 16rpx 0;
    margin-bottom: 10rpx;
    background-color: #e3e3e3;
    border-radius: 12rpx;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;

    font-family: OPPOSans, OPPOSans;
    font-weight: 400;
    font-size: 24rpx;
    color: #333333;

    &.active {
      background-color: #2e6140;
      color: #ffffff;
    }
    
    .tab-content {
      width: 100%;
      height: 100%;
    }
  }
}

.popup-content {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 40rpx;
}

.popup-title {
  font-size: 32rpx;
  font-weight: 600;
  text-align: center;
  margin-bottom: 40rpx;
}

.date-picker-container {
  margin-bottom: 40rpx;
}

.date-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
  
  text {
    width: 160rpx;
  }
  
  .picker-value {
    flex: 1;
    border: 1px solid #eee;
    border-radius: 8rpx;
    padding: 20rpx;

    width: 300rpx;
  }
}

.popup-buttons {
  display: flex;
  justify-content: space-between;
  
  .btn {
    width: 45%;
    padding: 20rpx 0;
    border-radius: 8rpx;
    text-align: center;
    font-size: 28rpx;
  }
  
  .cancel {
    background-color: #f5f5f5;
    color: #333;
  }
  
  .confirm {
    background-color: #2e6140;
    color: #fff;
  }
}
</style> 